<?php

namespace app\api\logic;

use app\api\cache\KeysUtil;
use app\api\cache\Marketing;
use app\api\cache\RedisCache;
use app\api\cache\SysCache;
use app\api\services\SysService;
use app\common\libs\Singleton;
use app\common\models\Sys\Feedback;
use app\common\models\Sys\Help;
use app\common\models\Sys\Notice;
use app\common\models\Sys\Qa;
use app\common\models\Sys\ShopConfig;
use app\common\models\Sys\Tabbar;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 系统模块
 * Class MemberLogic
 * @package app\api\logic
 */
class SysLogic extends BaseLogic
{
    use Singleton;

    /**
     * @param $helpId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function helpDetail($helpId): array
    {
        $where = [
            ['id', '=', $helpId],
            ['deleted', '=', 0],
        ];
        $list = Help::getInstance()
            ->where($where)
            ->field('id,title,content,create_at')
            ->find();

        if (!empty($list)) {
            $list = $list->toArray();
        } else {
            return [];
        }
        return $list;
    }

    /**
     * @param $keyword
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function helpList($keyword): array
    {
        $where = [
            ['deleted', '=', 0],
        ];
        if (!empty($keyword)) {
            $where[] = ['title', 'like', '%' . $keyword . '%'];
        }
        $list = Help::getInstance()
            ->where($where)
            ->field('id,title,content')
            ->order('id desc')
            ->select();

        if (!empty($list)) {
            $list = $list->toArray();
        } else {
            return [];
        }
        return ['rows' => $list];
    }

    /**
     * @return string[][]
     */
    public function helpType(): array
    {
        $commonList = [
            '售后未退款',
            '申请售后',
            '运费险',
            '账号申请',
        ];
        $hotList = [
            '售后未退款',
            '申请售后',
            '运费险',
            '账号申请',
        ];
        $newList = [
            '售后未退款',
            '申请售后',
            '运费险',
            '账号申请',
        ];

        return ['commonList' => $commonList, 'hotList' => $hotList, 'newList' => $newList];
    }

    /**
     * @param $type
     * @param $content
     * @param $imgList
     * @return bool
     */
    public function feedback($type, $content, $imgList): bool
    {
        $data = [
            'type' => $type,
            'content' => $content,
            'imgList' => $imgList,
        ];
        Feedback::getInstance()->insert($data);
        return true;
    }

    public function qa($keyword): array
    {
        $where = [
            ['deleted', '=', 0],
        ];
        if (!empty($keyword)) {
            $where[] = ['question', 'like', '%' . $keyword . '%'];
        }
        $list = Qa::getInstance()
            ->where($where)
            ->field('id,question,answer')
            ->order('sort desc')
            ->select();

        if (!empty($list)) {
            $list = $list->toArray();
        } else {
            return [];
        }
        return ['rows' => $list];
    }

    /**
     * @param $noticeId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function noticeDetail($noticeId): array
    {
        $where = [
            ['id', '=', $noticeId],
            ['status', '=', 1],
            ['deleted', '=', 0],
        ];
        $list = Notice::getInstance()
            ->where($where)
            ->field('id,title,detail,link,create_at')
            ->find();

        if (!empty($list)) {
            $list = $list->toArray();
        } else {
            return [];
        }
        return $list;
    }

    /**
     * @param $keyword
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function noticeList($keyword, $page, $pageSize): array
    {

        $where = [
            ['status', '=', 1],
            ['deleted', '=', 0],
            ['shop_id', '=', 0],
        ];
        if (!empty($keyword)) {
            $where[] = ['title', 'like', '%' . $keyword . '%'];
        }
        $list = Notice::getInstance()
            ->where($where)
            ->order('is_top desc,sort desc,create_at desc')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();

        if (!empty($list)) {
            $list = $list->toArray();
        } else {
            return [];
        }
        return ['rows' => $list];
    }

    /**
     * @param $articleId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function article($articleId): array
    {
        $article = SysCache::getArticleInfo($articleId);
        if (empty($article)) {
            $article = SysService::getInstance()->article($articleId);
            SysCache::setArticleInfo($articleId, $article);
        }

        return $article;
    }

    public function getArticle($key): array
    {
        $article = SysCache::getArticleInfo($key);
        if (empty($article)) {
            $article = SysService::getInstance()->getArticle($key);
            SysCache::setArticleInfo($key, $article);
        }

        return $article;
    }

    public function getCityByLongLat($lat, $lng)
    {
        $url = "http://api.map.baidu.com/geocoder?location={$lng},{$lat}";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_encode(simplexml_load_string($output));
        return json_decode($output, true);
    }

    public function advImg($type): array
    {
        $hotList = SysService::getInstance()->advImg($type);
        return ['rows' => $hotList];
    }

    public function areaCity($page, $pageSize, $letter, $name): array
    {
        $hotList = SysService::getInstance()->hotArea();
        $areaCity = SysService::getInstance()->areaCity($page, $pageSize, $letter, $name);
        return ['rows' => $areaCity, 'hotList' => $hotList];
    }

    public function area($pId): array
    {
        $area = SysService::getInstance()->area($pId);
        return ['rows' => $area];
    }

    /**
     * @return array
     */
    public function notice(): array
    {
        return SysService::getInstance()->getNotice();
    }

    /**
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function adv(): array
    {
        $list = SysService::getInstance()->getAdv();
//        foreach ($list as &$val) {
        //            $val['imgUrl'] = UrlConst::IMG_URL . $val['imgUrl'];
        //        }
        return ['rows' => $list];
    }

    public function nav(): array
    {
        $list = SysService::getInstance()->getNav();
//        foreach ($list as &$val) {
        //            $val['imgUrl'] = UrlConst::IMG_URL . $val['imgUrl'];
        //        }
        return ['rows' => $list];
    }

    public function tool(): array
    {
        $list = SysService::getInstance()->getTool();
        return ['rows' => $list];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function tabMenu(){
        $key = KeysUtil::getSystemConfigKey('app_tab_menu');
        $ret = RedisCache::get($key);
        if(empty($ret)){
            $where = [
                'deleted' => 0,
                'status' => 1,
            ];
            $tabbar = Tabbar::getInstance()->where($where)->order('sort desc,id asc')->select()->toArray();
            $ret = json_encode($tabbar, 256);
            RedisCache::set($key, $ret, 120);
        }
        return $ret ? json_decode($ret,1) : [];
    }

    public function transConfig(){
        $ret = RedisCache::hGetAll(KeysUtil::getSystemConfigKey('withdraw'));
        if (empty($ret)) {
            $config = ShopConfig::getInstance()->where('type', 'withdraw')->select();
            foreach ($config as $v) {
                RedisCache::hSet(KeysUtil::getSystemConfigKey('withdraw'), $v['configKey'], $v['configValue']);
                $ret[$v['configKey']] = $v['configValue'];
            }
        }
        foreach ($ret as $k => $v) {
            $ret[$k] = json_decode($v, true);
        }
        return $ret['balance'] ?? [];
    }
}
